from wechatpy.replies import TextReply, ImageReply
from flask import current_app
import re

from celery_task.email.tasks import send_mail
from .utils import get_media_id, get_weather, get_vtuber_info


def get_vtb_info(vname):
    pass


def get_access_token():
    wechat = current_app.wechat_client
    return wechat.access_token


class MessageHandler(object):
    """集中处理message对象的类"""

    @staticmethod
    def text(msg):
        content = msg.content
        config = current_app.config
        reply = None
        response_content = None

        # 发送图片
        if content.endswith('#') and content[:-1] in config['HANDLE_TEXT']:
            media_id = get_media_id(content[:-1])
            if media_id:
                reply = ImageReply(media_id=media_id, message=msg)
        # 天气情况
        if re.match(r'^天气 .{1,9}', content):
            response_content = get_weather(content[2:].strip())

        if re.match(r'^粽哥$', content):
            response_content = get_vtuber_info('粽哥')

        if reply:
            return reply
        if not response_content:
            response_content = content + ' peko'

        reply = TextReply(content=response_content, message=msg)
        xml = reply.render()
        return xml

    @staticmethod
    def image(msg):
        reply = ImageReply(media_id=msg.media_id, message=msg)
        xml = reply.render()
        return xml

    @staticmethod
    def event(msg):
        event = msg.event
        print(event)
        event_message = current_app.config['EVENT_MESSAGE']
        if event in event_message:
            follower = msg.source
            send_mail.delay(follower, event_message[event])

        reply = TextReply(content='关注成功' + ' peko', message=msg)
        xml = reply.render()
        return xml

    @classmethod
    def getxml(cls, msg):
        return getattr(cls, msg.type, None)(msg)


